#!/bin/bash
#
# FloatSmith top-level driver script. It checks for installation of the various
# tools needed (installing them if necessary) and then invokes the rest of the
# toolchain controlled by a Ruby script.
#

# set FLOATSMITH_HOME if necessary to run this script from a different folder
# (shouldn't be necessary in most cases; symbolic links will be resolved and
# you should be able just to link this script somewhere in your PATH)
#
if [ -z "$FLOATSMITH_HOME" ]; then
    export FLOATSMITH_HOME=$(dirname $(readlink -e ${BASH_SOURCE[0]}))
fi

echo "==  FloatSmith  =="
echo ""

# make sure Ruby is installed
if [ -z "$(command -v ruby)" ]; then
    echo "FloatSmith and CRAFT require Ruby, which generally needs to be installed by a sysadmin."
    echo "Please contact your admin and ask for access to Ruby 2.0 or newer."
    exit
fi

# basic system info
echo "System info: $(uname -a)"
echo "Using Ruby $(ruby -v | sed -e 's/ruby //')"
h=$(cd ${FLOATSMITH_HOME} > /dev/null ; git log -1 --pretty=format:"%h")
echo "FloatSmith located at: ${FLOATSMITH_HOME} (last commit $h)"

# set tools path
export FLOATSMITH_TOOLS="${FLOATSMITH_HOME}/tools"

# make sure CRAFT is installed and accessible
if [ -z "$(command -v craft)" ]; then
    if [ ! -e "${FLOATSMITH_TOOLS}/craft_env.sh" ]; then
        ${FLOATSMITH_TOOLS}/install_craft.sh
    fi
    source ${FLOATSMITH_TOOLS}/craft_env.sh
fi
v=$(craft | grep "CRAFT" | sed -e 's/CRAFT //')
h=$(cd $(dirname $(which craft)) > /dev/null ; git log -1 --pretty=format:"%h")
echo "Using CRAFT script: $(which craft) (version $v, last commit $h)"

# make sure ADAPT is installed and accessible
if [ -z "${CODIPACK_HOME}" ] || [ -z "${ADAPT_HOME}" ]; then
    if [ ! -e "${FLOATSMITH_TOOLS}/adapt_env.sh" ]; then
        ${FLOATSMITH_TOOLS}/install_adapt.sh
    fi
    source ${FLOATSMITH_TOOLS}/adapt_env.sh
fi
h=$(cd $CODIPACK_HOME > /dev/null ; git log -1 --pretty=format:"%h")
echo "Using CoDiPack located at: ${CODIPACK_HOME} (last commit $h)"
h=$(cd $ADAPT_HOME > /dev/null ; git log -1 --pretty=format:"%h")
echo "Using ADAPT located at: ${ADAPT_HOME} (last commit $h)"

# make sure TypeForge is installed and accessible
if [ -z "$(command -v typeforge)" ]; then
    if [ ! -e "${FLOATSMITH_TOOLS}/typeforge_env.sh" ]; then
        ${FLOATSMITH_TOOLS}/install_typeforge.sh
    fi
    source ${FLOATSMITH_TOOLS}/typeforge_env.sh
fi
v=$(typeforge --version | cut -d ' ' -f 3)
h=$(cd $(dirname $(which typeforge)) > /dev/null ; git log -1 --pretty=format:"%h")
echo "Using TypeForge executable: $(which typeforge) (version $v, last commit $h)"

# run interactive driver (there is a batch mode; see the Ruby source for info)
${FLOATSMITH_HOME}/scripts/driver.rb "$@"

